import { setToken, getToken } from '@/libs/util'
import http from '@/http'
import api from '@/http/api'

export default {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false
  },
  mutations: {
    setAvator (state, avatorPath) {
		localStorage.setItem('avatorImgPath',avatorPath)
      	state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      	state.userId = id
    },
    setUserName (state, name) {
      	state.userName = name
    },
    setAccess (state, access) {
      	state.access = access
    },
    setToken (state, token) {
      	state.token = token
      	setToken(token)
    },
    setHasGetInfo (state, status) {
      	state.hasGetInfo = status
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password}) {
		userName = userName.trim()
		return new Promise((resolve, reject) => {
			http.post(api.LoginApi(),{
				userName,
				password
			}).then(res => {
				if(res.data.code='00'){
					const data=res.data.data
					console.log(data)
					commit('setToken', data.token)
					commit('setAvator', data.avator)
					commit('setUserName', data.name)
					commit('setUserId', data.user_id)
					commit('setAccess', data.access)
					commit('setHasGetInfo', true)
					resolve(data)
				}else{
					reject(res.data)
				}
			})
			.catch(err=>{
				reject(err)
			})
		})
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
		return new Promise((resolve, reject) => {
			// 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
			commit('setToken', '')
			commit('setAccess', [])
			resolve()
		})
    },
  }
}
